package com.devperson.io.bio.ServiceSocket;

import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 功能描述:
 *
 * @author lixiaomeng
 * @date 2018/12/14
 */
public class BIoServiceSocket {


    public static void main(String[] args) throws IOException {
        boolean flag = true;
        ServerSocket serverSocket = new ServerSocket( 9999);
        System.out.println("服务端服务已经启动，监听端口为： 9999");
        ExecutorService executors = Executors.newFixedThreadPool(10);
        while (flag) {
            Socket socket =  serverSocket.accept();
            executors.submit(new ClientSocketHandle(socket));
        }
        executors.shutdown();
        serverSocket.close();
    }

    public static class ClientSocketHandle implements Runnable {

        private Socket client;

        private Scanner scanner;

        private PrintStream outputStream;

        private boolean flag = true;

        public ClientSocketHandle(Socket clientSocket) {
            try {
                this.client = clientSocket;
                this.scanner = new Scanner(clientSocket.getInputStream());
                scanner.useDelimiter("\n");
                this.outputStream =new PrintStream( clientSocket.getOutputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        @Override
        public void run() {
            while (flag) {
                if (scanner.hasNext()) {
                    String str = scanner.nextLine().trim();
                    System.out.println(str);
                    if ("byebye".equalsIgnoreCase(str)) {
                        System.out.println("byebye。。。。。。。。");
                        this.outputStream.println("byebye");
                        this.flag = false;

                    } else {
                        this.outputStream.println(" [ECHO]: " + str);
                    }
                }
            }
            try {
                this.client.close();
                this.outputStream.close();
                this.scanner.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
